<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-06-05
 * Time: 17:14
 */

namespace app\common\service\traits;

use app\api\model\mp\v1\OrderSubscribeMessage;
use app\common\enum\OrderEnum;
use app\common\model\Order as OrderModel;
use think\facade\Queue;
use WeChat\Contracts\Tools;
//use think\facade\Log;

trait WxPayNotify
{
    /**
     * 处理支付成功后微信服务器的返回信息
     * @param $data
     * @param bool $is_send_template 是否发生消息给用户
     */
    protected function handlePaySuccessNotify($data, $is_send_template = false)
    {
        $orderNo = $data['out_trade_no'];   // 订单编号
        $transaction_id = $data['transaction_id']; // 微信支付订单号

        Queue::push('app\common\job\PaySuccessNotifyQueue', [
            'order_no' => $data['out_trade_no'],   // 订单编号
            'transaction_id' => $data['transaction_id'],    // 微信支付订单号
            'attach' => $data['attach'],
            'is_send_template' => $is_send_template    // 是否发送消息给用户
        ], 'wx_pay_success_queue');

        // 判断订单是否存在或者是否为已提交状态
//        if (OrderModel::checkOrderStatusByOrderNo($orderNo,OrderEnum::CREATE_ORDER)) {
//            // 更新订单信息
//            OrderModel::updateByOrderNo($orderNo, ['transaction_id','status'], [
//                'transaction_id' => $transaction_id,
//                'status' => OrderEnum::PAY_SUCCESS,
//            ]);
//
//             // 根据订单编号查询订单信息
//            $orderData = OrderModel::getOrderDataByOrderNo($orderNo,['title','amount','allow_pay_subscribe','create_time']);
////
////            // 判断当前返回的附加数据上是否有数据
////            if (!empty($data['attach'])) {
////                $data['attach'] = json_decode($data['attach'],true);
////                if (isset($data['attach']['type'])) {
////                    // 判断当前附加数据的类型
////                    switch ($data['attach']['type']) {
////                        default:
////                            break;
////                    }
////                }
////
////            }
//
//            if ($is_send_template && $orderData['allow_pay_subscribe'] === 1) {
//                (new OrderSubscribeMessage())->sendOrderSubscribeMessage(
//                    'pay',
//                    $orderData['user']['openid'],
//                    [
//                        'order_no' => $orderData['order_no'],
//                        'title' => $orderData['title'],
//                        'amount' => $orderData['amount'],
//                        'create_time' => $orderData['create_time']
//                    ]);
//            }
//
//        }
    }

    /**
     * 处理退款后微信服务器返回的信息
     * @param $data
     * @param bool $is_send_template 是否发生消息给用户
     */
    protected function handleRefundOrderNotify($data, $is_send_template = false)
    {
        // 处理发起退款的是否为当前的应用
        if ($data['appid'] != $this->config['appid']) {
            return ;
        }

        Queue::push('app\common\job\PayRefundNotifyQueue', [
            'decode' => Tools::xml2arr($this->refundDecrypt($data['req_info'])),   // 对微信服务器传回的数据进行解密
            'is_send_template' => $is_send_template    // 是否发送消息给用户
        ], 'wx_pay_refund_queue');

//        $data['decode'] = Tools::xml2arr($this->refundDecrypt($data['req_info']));
//        if (OrderModel::checkOrderStatusByOrderNo($data['decode']['out_trade_no'],OrderEnum::CREATE_REFUND)) {
//            $updateData = [];
//
//            switch ($data['decode']['refund_status']) {
//                case 'SUCCESS' :
//                    $updateData['status'] = OrderEnum::REFUND_SUCCESS;
//                    break;
//                case 'CHANGE' :
//                    $updateData['status'] = OrderEnum::REFUND_CHANGE;
//                    break;
//                case 'REFUNDCLOSE' :
//                    $updateData['status'] = OrderEnum::REFUND_CLOSE;
//                    break;
//            }
//
//            // 更新订单信息
//            OrderModel::updateByOrderNo($data['decode']['out_trade_no'], ['status'], $updateData);
//
//            if ($updateData['status'] == OrderEnum::REFUND_SUCCESS) {
//                // 向用户发送退款成功消息模版
//                $orderData = OrderModel::getOrderDataByOrderNo($data['decode']['out_trade_no'],['title','refund_desc','refund_amount','allow_refund_subscribe','refund_create_time']);
////
////                // 根据不同的订单类型处理不同处理
////                switch ($orderData['type']) {
////                    case OrderType::H5_TEMPLATE :
////                        // 退款成功后删除该用户的模版数据
////                        H5TemplateDataModel::where(['order_id' => $orderData['id']])
////                            ->find()
////                            ->delete();
////                        break;
////                }
//
//                if ($is_send_template && $orderData['allow_refund_subscribe'] === 1) {
////                    Log::record('|refund_create_time' . $orderData['refund_create_time'], 'error');
//                    (new OrderSubscribeMessage())->sendOrderSubscribeMessage(
//                        'refund',
//                        $orderData['user']['openid'],
//                        [
//                            'order_no' => $orderData['order_no'],
//                            'title' => $orderData['title'],
//                            'refund_desc' => $orderData['refund_desc'],
//                            'refund_amount' => $orderData['refund_amount'],
//                            'refund_create_time' => $orderData['refund_create_time']
//                        ]);
//                }
//
//            }
//
//        }
    }



    /**
     * 对退款的req_info字段进行解密
     * @param $str
     * @return bool|string
     */
    protected function refundDecrypt($str)
    {
        $key = md5($this->config['mch_key']);
        $str = base64_decode($str);
//        $str = openssl_decrypt($str, 'AES-256-ECB', $key, OPENSSL_RAW_DATA);
//        return $str;
        if (check_php_version('7.2')) {
            $str = openssl_decrypt($str, 'AES-256-ECB', $key, OPENSSL_RAW_DATA);
            return $str;
        } else {
            $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);
            $block = mcrypt_get_block_size('rijndael_128', 'ecb');
            $pad = ord($str[($len = strlen($str)) - 1]);
            $len = strlen($str);
            $pad = ord($str[$len - 1]);
            return substr($str, 0, strlen($str) - $pad);
        }
    }
}